package com.lagou.edu.filter;

import com.lagou.edu.mapper.LoginMapper;
import io.netty.handler.codec.http.cookie.Cookie;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;

/**
 * 定义全局过滤器，会对所有路由生效
 */
@Slf4j
@Component  // 让容器扫描到，等同于注册了
public class LoginTokenFilter implements GlobalFilter, Ordered {

    @Autowired
    LoginMapper loginMapper;

    // 模拟黑名单（实际可以去数据库或者redis中查询）
    private static List<String> blackList = new ArrayList<>();

    static {
        blackList.add("0:0:0:0:0:0:0:1");  // 模拟本机地址
    }

    /**
     * 过滤器核心方法
     * @param exchange 封装了request和response对象的上下文
     * @param chain 网关过滤器链（包含全局过滤器和单路由过滤器）
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 思路：获取客户端ip，判断是否在黑名单中，在的话就拒绝访问，不在的话就放行
        // 从上下文中取出request和response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

     /*   MultiValueMap<String, HttpCookie> cookies = request.getCookies();
        List<HttpCookie> gateWayLogin = cookies.get("gateWayLogin");
        HttpCookie httpCookie = gateWayLogin.get(0);
        String gateWayLogin1 = httpCookie.getValue();*/
        HttpHeaders headers = request.getHeaders();
        boolean gateWayLogin = headers.containsKey("gateWayLogin");
        List<String> gateWayLogins = new ArrayList<>();
        if(gateWayLogin){
             gateWayLogins = headers.get("gateWayLogin");
        }
        String gateWayLogina = new String();
        if(gateWayLogins.size()> 0){
            gateWayLogina = gateWayLogins.get(0);
        }
        String token = loginMapper.getToken(gateWayLogina);
        if(token != null){
            return chain.filter(exchange);
        }else{
            String result = "dataRequest be denied!";
            DataBuffer wrap = response.bufferFactory().wrap(result.getBytes());
            return response.writeWith(Mono.just(wrap));
        }
        /**
         * 在数据库中获取token，是否和前端页面的一致，一致再通行，不一致，直接返回
         */
    }

    /**
     * 返回值表示当前过滤器的顺序(优先级)，数值越小，优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return 1;
    }
}
